<template>
  <div class="knowledge-qa-container">
    <!-- 上方：显示问题和答案 -->
    <div class="qa-list">
      <el-card v-for="(qa, index) in qaList" :key="index" class="qa-item">
        <div class="question"  v-html="renderMarkdown(qa.question)"></div>
        <div class="answer" v-html="renderMarkdown(qa.answer)"></div>
      </el-card>

      <!--答案下方是引用-->
      <div v-if="references.length >0"  class="references">
      <h4>引用来源：</h4>
      <ul>
        <li v-for="ref in references" :key="ref.file_id">
          <a :href="ref.file_url" target="_blank">{{ ref.file_name }}</a>
        </li>
      </ul>
    </div>
    </div>

    <!-- 下方：提问框 -->
    <div class="ask-box">
      <el-input
        v-model="question"
        placeholder="请输入你的问题"
        @keyup.enter="handleAsk"
      >
        <template #append>
          <el-button type="primary" @click="handleAsk">提问</el-button>
        </template>
      </el-input>
    </div>
  </div>
</template>

<script setup>
import { ref , onMounted} from 'vue';
import { ElMessage } from 'element-plus';
import { chatQuestion,chatHistory } from '@/api/chat';
import { router } from 'vue-router';
import { ElLoading } from 'element-plus';
import { marked, Marked } from 'marked';
import DOMPurify from 'dompurify';


//配置 marked
marked.setOptions({
  breaks: true,
  gfm : true,
});

// 模拟的问答数据
const qaList = ref([
  { question: '', answer: '' },
]);

// 新问题
const question = ref('');
//引用列表
const references = ref([]);

//Markedown 渲染方式
const renderMarkdown = (content) => {
  return DOMPurify.sanitize(marked.parse(content || ''));
};

const fetchHistory = async () => {
  console.log("访问历史记录fetchHistory")
  const token = localStorage.getItem("token");
  console.log('token:', token);
  try {
    const response = await chatHistory(token);
    console.log('调用成功的id:',token);
    const history = response.data;
    console.log('history:', history);
    qaList.value = history;
  } catch (error) {
    console.error('获取历史记录失败', error);
  }
};



onMounted(() => {
  console.log("访问历史记录fetchHistory")
  fetchHistory();
});






// 处理提问
const handleAsk = async () => {
    if (!question.value.trim()) {
      ElMessage.warning('请输入问题');
      return;
    }
    const token = localStorage.getItem("token");
  
    if (!token) {
    ElMessage.warning('请先登录');
    return router.push('/login');
    }
    let loadingInstance = null;
      try{
      //显示加载状态
        loadingInstance = ElLoading.service({
        lock: true,
        text: 'AI思考中...',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      // 调用AI接口
      const response =  await chatQuestion({
        question:question.value,
        token});
      console.log(response.data)
      
      const answer = response.data.answer;
      references.value = response.data.fileDTO;
      qaList.value.push({ question: question.value, answer });
      question.value = ''; // 清空输入框
      }catch(error){
        console.error('AI调用失败',error);
      }finally{
        //关闭加载状态
        loadingInstance.close();
      }
  };
</script>

<style scoped>
.knowledge-qa-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.qa-list {
  margin-bottom: 20px;
}

.qa-item {
  margin-bottom: 10px;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.question {
  font-size: 16px;
  margin-bottom: 10px;
}

.answer {
  font-size: 14px;
  color: #666;
}

.ask-box {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  width: 100%;
  max-width: 800px;
  background: white;
  padding: 10px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}
/* Markdown 内容样式 */
.markdown-content {
  line-height: 1.6;
}

.markdown-content :deep(h1),
.markdown-content :deep(h2),
.markdown-content :deep(h3) {
  margin: 1em 0 0.5em 0;
  color: #333;
}

.markdown-content :deep(p) {
  margin: 0.5em 0;
}

.markdown-content :deep(ul),
.markdown-content :deep(ol) {
  padding-left: 2em;
  margin: 0.5em 0;
}

.markdown-content :deep(blockquote) {
  border-left: 3px solid #ddd;
  padding-left: 1em;
  color: #666;
  margin: 0.5em 0;
}

.markdown-content :deep(code) {
  background: #f5f5f5;
  padding: 0.2em 0.4em;
  border-radius: 3px;
  font-family: monospace;
}

.markdown-content :deep(pre) {
  background: #f8f8f8;
  padding: 1em;
  border-radius: 4px;
  overflow: auto;
}

.markdown-content :deep(pre code) {
  background: none;
  padding: 0;
}

.markdown-content :deep(strong) {
  font-weight: bold;
}

.markdown-content :deep(em) {
  font-style: italic;
}

.markdown-content :deep(a) {
  color: #409eff;
  text-decoration: none;
}

.markdown-content :deep(a:hover) {
  text-decoration: underline;
}
</style>